package com.archive.forum.controller;

import com.archive.forum.mapper.UserMapper;
import com.archive.forum.model.User;

import com.archive.forum.service.UserService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class RegisterController {
    @Autowired
    private UserService userService;
    //注册
    @GetMapping("/register")
    public String register() {
        return "register";
    }
    @PostMapping("/register")
    public String doRegister(@RequestParam(name = "name",required = false) String name,
                             @RequestParam(name = "nickname",required = false) String nickname,
                             @RequestParam(name = "password",required = false) String password,
                             HttpServletResponse response,
                             Model model) {
        if (name == null || name.isEmpty() || nickname == null || nickname.isEmpty() || password == null || password.isEmpty()) {
            model.addAttribute("error", "请填写完整信息");
            return "register";
        }

        if (userService.isExist(name)) {
            model.addAttribute("error", "用户名已存在");
            return "register";
        }

        User user = new User();
        user.setName(name);
        user.setNickname(nickname);
        user.setPassword(userService.sha1(password));
        userService.register(user,response);
        return "redirect:/";
    }
}

